﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NH = NHibernate;

namespace Laugh.Data
{
    public class DataTransaction : ITransaction
    {
        NH.ITransaction _transaction;
        bool isOriginator = true;

        public DataTransaction(NH.ISession session)
        {
            _transaction = session.Transaction;
            if (_transaction.IsActive)
                isOriginator = false;
            // The method that first opened the transaction should also close it            
            else
                _transaction.Begin();
        }

        #region ITransaction Members
        public void Commit()
        {
            if (isOriginator && !_transaction.WasCommitted && !_transaction.WasRolledBack)
                _transaction.Commit();
        }

        public void Rollback()
        {
            if (!_transaction.WasCommitted && !_transaction.WasRolledBack)
                _transaction.Rollback();
        }

        #endregion

        #region IDisposable Members

        void IDisposable.Dispose()
        {
            if (isOriginator)
            {
                Rollback();
                _transaction.Dispose();
            }
        }

        #endregion
    }
}
